from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_script_editor_dialog import Ui_Dialog_script_editor
from app.window.msg_box import Msg_box
import time
from database.db import Database


class Script_editor_signal(QObject):
    update_script_data = Signal(int,dict)


class Private_script_editor_dialog(QDialog):
    
    def __init__(self, parent=None):
        super(Private_script_editor_dialog, self).__init__(parent)
        self.ui = Ui_Dialog_script_editor()
        self.ui.setupUi(self)
        
        self.setWindowTitle('私有脚本编辑器')
        
        self.ui.label_group.hide()
        self.ui.comboBox_group.hide()

        self.setModal(True)  # 设置窗体为模态窗口，必须为True
        self.setWindowFlags(Qt.WindowCloseButtonHint)  # 设置窗体仅显示关闭按钮
    
        self.msg = Msg_box(self)
        self.signal = Script_editor_signal()
        self.script_id = -1

        self.ui.pushButton_save.clicked.connect(self.save)
    


    def slot_show(self,script_id:int):
        self.script_id = script_id
        # 查询数据
        db = Database()
        data = {}
        s_data = db.select('scripts',['name','info','content','textfsm'],f'id={script_id}')[0]
        if s_data is not None:
            data['id'] = script_id
            data['name'] = s_data[0]
            data['info'] = s_data[1]
            data['content'] = s_data[2]
            data['textfsm'] = s_data[3]
            self.ui.lineEdit_name.setText(data['name'])
            self.ui.textEdit_info.setText(data['info'])
            self.ui.textEdit_script.setText(data['content'])
            self.ui.textEdit_textfsm.setText(data['textfsm'])

        db.close_conn()
        self.show()


    def save(self):
        data = {
            'name' : self.ui.lineEdit_name.text(),  
            'info' : self.ui.textEdit_info.toPlainText(),
            'content' : self.ui.textEdit_script.toPlainText(),
            'textfsm' : self.ui.textEdit_textfsm.toPlainText(),
        }
        # 数据库更新
        db = Database()
        cur_time = time.localtime()
        cur_time = time.strftime('%Y-%m-%d %H:%M:%S',cur_time)
        fields = ['name','content','textfsm','info',]
        vlues = (data['name'],data['content'],data['textfsm'],data['info'],self.script_id)
        db.update('scripts',fields,vlues,f'id={self.script_id}')

        db.close_conn()

        self.signal.update_script_data.emit(self.script_id,data)

        self.hide()
